import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {
    AlertController, DateTime, IonicPage, ItemSliding, NavController, NavParams, Select,Content,Events
} from 'ionic-angular';

import * as moment from 'moment';
import $ from 'jquery'

import {ScheduleListProvider} from "../../../providers/schedule/schedule-list/schedule-list.provider";
import {ScheduleAddPage} from "../schedule-add/schedule-add";
import {AdpCalendarMonthComponent} from "../../../components/common/adp-calendar-month/adp-calendar-month.component";
import {MouthData} from "../../../model/pages/schedule/schedule-list/schedule-list.model";
import {SideMenuService} from "../../../services/common/side-menu.service";
import {ScheduleItem} from '../../../model/pages/schedule/schedule-add/schedule-add.model';
import {DateService} from '../../../services/common/date.service';

@IonicPage()
@Component({
    selector: 'page-schedule-list',
    templateUrl: 'schedule-list.html',
    providers: [
        ScheduleListProvider,
        SideMenuService,
        DateService
    ]
})
export class ScheduleListPage {
    @ViewChild(AdpCalendarMonthComponent) calendar: AdpCalendarMonthComponent;
    @ViewChild('datetimePicker') datetimePicker: DateTime;
    @ViewChild('delRule') delRule: Select;
    @ViewChild(Content) content: Content;

    pickerOptions = {
        cssClass: 'schedule-list-picker'
    };
    sixLine: boolean = false;
    moment = moment;//日期格式化库

    currentTimestap: number;

    loading: boolean = false;

    get nextDay() {
        return this.currentTimestap + 24 * 60 * 60
    }

    monthData: MouthData[] = [];
    dayList: Array<any> = [];

    year: number;//头部年份

    month: number;//头部月份

    datetime: string;//日历弹框日期字符串:2017-8-30

    // 当前所要删除的日程
    delSchedule:ScheduleItem=new ScheduleItem();
    // 删除提示弹框
    delRuleOption = [{value: 0, str: '仅删除此日程'}, {value: 1, str: '删除所有将来日程'}];

    // header 高度
    headerHeight:number;
    // 视图数据请求
    viewDataStatus:boolean;
    // 年度列表
    private yearList:any[]=[];

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public alertCtrl: AlertController,
                private sideMenuService: SideMenuService,
                private ref: ChangeDetectorRef,
                private scheduleListProvider: ScheduleListProvider,
                private dateService:DateService,
                private event:Events
                ) {
        this.yearList=this.dateService.getYearList(2010);
    }

    queryData() {
        this.getMouthData(this.calendar.startTimestamp, this.calendar.endTimestamp);
        this.getDayData(this.currentTimestap);
    }

    ionViewDidEnter() {
        //this.queryData();
        this.calendar.setSelect(this.currentTimestap);
        this.content.scrollToTop();
        setTimeout(() => {
            this.headerHeight = $('.schedule-header-self')[$('.schedule-header-self').length-1].clientHeight;
            this.checkContentMargin();
        }, 200)
    }


    openDatetime() {
        this.datetimePicker.open();
    }

    /**
     * 选择日历弹框
     * @param event
     */
    selectDatetime(event) {
        this.year = event.year;
        this.month = event.month;
        this.currentTimestap = moment(new Date(event.year, event.month - 1)).unix();
        this.calendar.createMonth(event.year, event.month - 1);
        this.calendar.setDate(this.currentTimestap);
        this.sixLine = this.calendar.dateArray.length > 40;
        this.queryData();
    }

    backButtonClick(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.navCtrl && this.navCtrl.pop(null, null);
    }

    goToday() {
        this.calendar.goToday();
        this.currentTimestap = moment(new Date(moment().year(), moment().month(), moment().date())).unix();
        this.getMouthData(this.calendar.startTimestamp, this.calendar.endTimestamp);
        this.getDayData(this.currentTimestap);
        //this.datetime=moment(new Date(moment().year(), moment().month(), moment().date())).toISOString();
    }

    onDaySelect(event) {
        this.year = event.year;
        this.month = event.month + 1;
        this.currentTimestap = moment(new Date(event.year, event.month, event.date)).unix();
        this.getDayData(this.currentTimestap);
        this.calendar.setSelect(this.currentTimestap);
        this.getMouthData(this.calendar.startTimestamp, this.calendar.endTimestamp);
    }

    /**
     * 获取时间样式
     * @param {number} startTime
     * @param {number} endTime
     * @returns {string}
     */
    getStyleTime(startTime: number, endTime: number): string {
        const nowTimestamp = moment(new Date()).unix();
        let className: string;
        if (endTime < nowTimestamp) {
            className = 'isPass';
        } else if (startTime < nowTimestamp && nowTimestamp < endTime) {
            className = 'isNow';
        } else if (nowTimestamp < startTime) {
            className = '';
        }
        return className;
    }

    getMouthData(startTimestamp: number, endTimestamp: number) {
        this.scheduleListProvider.getMouthData(startTimestamp, endTimestamp).subscribe(res => {
            this.monthData = res;
            this.viewDataStatus=true;
            this.checkContentMargin();
        }, (error) => {
            this.checkContentMargin();
            this.viewDataStatus=true;
        });
    }

    getDayData(currentTimestap: number) {
        this.dayList = [];
        this.loading = true;
        this.scheduleListProvider.getDayData(currentTimestap).subscribe(res => {
            this.dayList = this.scheduleListProvider.parseDayData(res);
            this.checkContentMargin();
            // this.dayList = res
            this.loading = false;
        }, (error) => {
        });
    }

    // 当header高度变化时手动修改ion-content\fixed-content的margin-top值
    checkContentMargin(){
        let header=$('.schedule-header-self')[$('.schedule-header-self').length-1].clientHeight;
        if(this.headerHeight!=header){
            $('.schedule-content-self div.fixed-content')[$('.schedule-content-self div.fixed-content').length-1].style.marginTop=header+'px';
            $('.schedule-content-self div.scroll-content')[$('.schedule-content-self div.scroll-content').length-1].style.marginTop=header+'px';
            this.headerHeight=$('.schedule-header-self')[$('.schedule-header-self').length-1].clientHeight;
        }
    }

    isCurrentDay(item) {
        //开始时间选中日，结束时间是选中日<(正常表示)
        return this.scheduleListProvider.isCurrentDay(item)
    }

    isAllDay(item): boolean {
        //开始时间选中日之前<=，结束时间是选中日之后>=（表示为全天）
        return this.scheduleListProvider.isAllDay(item)
    }

    isStartDay(item) {
        //开始时间今天>=，结束时间是今天之后>(显示为开始)(排除全天)
        return this.scheduleListProvider.isStartDay(item)
    }

    isEndDay(item) {
        //开始时间选中日之前<=，结束时间是选中日<(显示为结束)
        return this.scheduleListProvider.isEndDay(item)
    }

    deleteSchedule(item, slidingItem: ItemSliding) {
        this.delSchedule=item;
        console.log(this.delSchedule);
        if(this.delSchedule.frequency==1){
            let fnOk = () => this.selDelRule(0);
            let fnCancel = () => {
                slidingItem.close();
            };
            this.deleteConfirm('确认删除？', fnOk, fnCancel);
            return false;
        }else{
            slidingItem.close();
            this.delRule.open();
        }
    }

    goToAddSchedule() {
        this.navCtrl.push('ScheduleAddPage', {date: this.currentTimestap})
    }

    goToDetail(id: number, item: any) {
        let data=JSON.parse(JSON.stringify(item));
        this.navCtrl.push('ScheduleAddPage', {id: id, date: this.currentTimestap, item: data})
    }

    deleteConfirm(message: string, okHandler: Function, cancelHandler: Function) {
        let confirm = this.alertCtrl.create({
            message: message,
            buttons: [{
                text: '取消',
                handler: () => {
                    cancelHandler();
                }
            }, {
                text: '确定',
                handler: () => {
                    okHandler();
                }
            }]
        });
        confirm.present();
    }

    // 删除
    selDelRule(value){
        this.delSchedule.delRule=value;
        this.scheduleListProvider.deleteSchedule(this.delSchedule.id,this.currentTimestap,this.delSchedule.delRule).subscribe((res)=>{
            this.queryData();
            this.delSchedule.delRule=null;
            this.ref.detectChanges();
        })
    }
}
